package com.tonann.app.service.impl;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.tonann.app.VO.ProjectDeviceVO;
import com.tonann.app.domain.AppDevice;
import com.tonann.app.domain.AppProject;
import com.tonann.app.mapper.AppProjectMapper;
import com.tonann.app.minio.MinioService;
import com.tonann.app.service.IAppDeviceService;
import com.tonann.app.service.IAppProjectService;
import com.tonann.common.annotation.ProjectDataScope;
import com.tonann.common.annotation.SensorDataScope;
import com.tonann.common.core.domain.entity.SysDept;
import com.tonann.common.utils.DateUtils;
import com.tonann.common.utils.SecurityUtils;
import com.tonann.system.service.ISysDeptService;
import com.tonann.system.service.ISysDictDataService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 项目管理Service业务层处理
 *
 * @author tonann
 * @date 2023-03-19
 */
@Service
public class AppProjectServiceImpl implements IAppProjectService {
    @Resource
    private  AppProjectMapper appProjectMapper;
    @Resource
    private  IAppDeviceService appDeviceService;
    @Resource
    private  ISysDictDataService sysDictDataService;
    @Resource
    private  MinioService minioService;

    /**
     * 查询项目管理
     *
     * @param projectId 项目管理主键
     * @return 项目管理
     */
    @Override
    public AppProject selectAppProjectByProjectId(Long projectId) {
        return appProjectMapper.selectAppProjectByProjectId(projectId);
    }

    /**
     * 查询项目管理列表
     *
     * @param appProject 项目管理
     * @return 项目管理
     */
    @Override
    public List<AppProject> selectAppProjectList(AppProject appProject) {
        return appProjectMapper.selectAppProjectList(appProject);
    }

    /**
     * 新增项目管理
     *
     * @param appProject 项目管理
     * @return 结果
     */
    @Override
    public int insertAppProject(AppProject appProject) throws Exception {
        appProject.setCreateTime(DateUtils.getNowDate());
        if (appProject.getProjectCode() == null){
            throw  new Exception("项目编号为空");
        }else {
           if (selectAppProjectByProjectCode(appProject.getProjectCode()) != null){
               throw  new Exception("项目编号重复");
           }
        }
        if (appProject.getProjectImage() != null && appProject.getProjectCode() != null){
            createAppQR(appProject);
        }
        return appProjectMapper.insertAppProject(appProject);
    }

    private void createAppQR(AppProject appProject) {
        String url = appProject.getProjectImage();
        if (!url.contains("http")){
            url = "http://59.110.170.159:9000/threedegree/20240812/1723431760370_WechatIMG1326.jpg";
        }
        String content = "https://www.tonann.cn/app/app.html?projectCode=" + appProject.getProjectCode();
        try {
            QrConfig qrConfig = new QrConfig();
            BufferedImage bufferedImg = ImageIO.read(new URL(url));
            qrConfig.setImg(bufferedImg);
            qrConfig.setRatio(4);
            BufferedImage bufferedImage =  QrCodeUtil.generate(content,qrConfig);
            String filePath  = minioService.uploadBufferImage(bufferedImage);
            if (filePath.contains("?")){
                filePath = filePath.substring(0,filePath.indexOf("?"));
            }
            appProject.setAppQR(filePath);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 修改项目管理
     *
     * @param appProject 项目管理
     * @return 结果
     */
    @Override
    public int updateAppProject(AppProject appProject) throws Exception {
        AppProject project = selectAppProjectByProjectId(appProject.getProjectId());
        if(appProject.getProjectCode() != null && project.getProjectCode() != null && !appProject.getProjectCode().equals(project.getProjectCode())) {
            if (selectAppProjectByProjectCode(appProject.getProjectCode()) != null) {
                throw new Exception("项目编号重复");
            }
        }
        if (project != null && project.getProjectCode() != null && appProject.getProjectImage() != null && (
                (project.getProjectImage() == null) ||
                        !Objects.equals(appProject.getProjectImage(), project.getProjectImage()))
            ){
            createAppQR(appProject);
        }
        return appProjectMapper.updateAppProject(appProject);
    }

    /**
     * 批量删除项目管理
     *
     * @param projectIds 需要删除的项目管理主键
     * @return 结果
     */
    @Override
    public int deleteAppProjectByProjectIds(Long[] projectIds) {
        return appProjectMapper.deleteAppProjectByProjectIds(projectIds);
    }

    /**
     * 删除项目管理信息
     *
     * @param projectId 项目管理主键
     * @return 结果
     */
    @Override
    public int deleteAppProjectByProjectId(Long projectId) {
        return appProjectMapper.deleteAppProjectByProjectId(projectId);
    }

    @Override
    public AppProject selectAppProjectByProjectCode(String projectCode) {
        return appProjectMapper.selectAppProjectByProjectCode(projectCode);
    }

    @Override
    public ProjectDeviceVO selectProjectDeviceByProjectCode(String projectCode) {
        AppProject appProject = appProjectMapper.selectAppProjectByProjectCode(projectCode);
        ProjectDeviceVO vo = new ProjectDeviceVO();
        if (appProject != null){
            String envType = sysDictDataService.selectDictValue("app_device_type", "房间环境");
            AppDevice device = new AppDevice();
            device.setProjectId(appProject.getProjectId());
            List<AppDevice> projectDevice = appDeviceService.selectAppDeviceList(device);
            vo.setDeviceList(projectDevice);
            vo.setTotalDeviceNum(projectDevice.size());
            Integer running = 0;
            Integer alarm = 0;
            Integer envTotal = 0;
            Integer envRunning = 0;
            Integer envException = 0;
            for(AppDevice appDevice : projectDevice){
                if (appDevice.getIsRunning().equals("1")){
                    running++;
                }
                if (appDevice.getIsException().equals("1")){
                    alarm++;
                }
                if (appDevice.getType().equals(envType)){
                    envTotal++;
                    if (appDevice.getIsException().equals("1")){
                        envException++;
                    }
                }
            }
            vo.setTotalRunningDeviceNum(running);
            vo.setTotalAlarmDeviceNum(alarm);
            vo.setTotalCloseDeviceNum(vo.getTotalDeviceNum() - running);
            vo.setTotalEnvNum(envTotal);
            vo.setTotalEnvRunningNum(envTotal - envException);
            vo.setTotalEnvAlarmNum(envException);
        }
        return  vo;
    }

    @Override
    public List<AppProject> selectAppProjectByProjectName(String projectName) {
        projectName = projectName.trim();
        AppProject project = new AppProject();
        project.setProjectName(projectName);
        return appProjectMapper.selectAppProjectList(project);
    }
}
